package com.tros.customer.features;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.tros.customer.notification.MailNotification;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.io.File;

/**
 * Servlet implementation class ChequeDeposit
 */
@WebServlet("/ChequeDeposit")
public class ChequeDeposit extends HttpServlet {
	private static final long serialVersionUID = 1L;
	File chq ;
	int File_size = 5000 * 1024;
	int Mem = 5000 * 1024;	
	String accType ="";
	String accno="";
	String chkno="";
	String transno="";
	String chkamt="";
	
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ChequeDeposit() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
        System.out.println("came here doPost");
		
		try{
			 System.out.println("came here doPost calling cheque");
			 UploadCheque(request, response);
		}catch(Exception e)
		{
			System.out.println("--------> error enna"+e.getMessage());
		}
	}

	private void UploadCheque(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		
		ServletContext text = this.getServletContext(); 
		HttpSession ses = request.getSession();
		String chqPath = text.getInitParameter("cheque-upload");
		
		DiskFileItemFactory fact = new DiskFileItemFactory();		      
	    fact.setSizeThreshold(Mem);		     
	    fact.setRepository(new File("d:\\temp"));
	    
	    ServletFileUpload up = new ServletFileUpload(fact);
	    up.setSizeMax( Mem );
	    
	      try{ 
	         
	         List Items = up.parseRequest(request);
	         Iterator iterItems = Items.iterator();

	         while ( iterItems.hasNext () ) 
	         {
	            FileItem fileItemsPresent = (FileItem)iterItems.next();
	            System.out.println("----------> here name ->"+fileItemsPresent.getFieldName());
	            
	            if(fileItemsPresent.getFieldName().equals("accType"))
	            {
	            	this.accType = fileItemsPresent.getString();
	            	System.out.println("----------> here name accType ->"+fileItemsPresent.getString());
	            }
	            
	            
	            if(fileItemsPresent.getFieldName().equals("accno"))
	            {
	            	this.accno = fileItemsPresent.getString();
	            	System.out.println("----------> here name accno ->"+fileItemsPresent.getString());	            	
	            }
	            
	            if(fileItemsPresent.getFieldName().equals("chkno"))
	            {
	            	this.chkno = fileItemsPresent.getString();
	            	System.out.println("----------> here name chkno ->"+fileItemsPresent.getString());
	            }
	            
	            if(fileItemsPresent.getFieldName().equals("transno"))
	            {
	            	this.transno = fileItemsPresent.getString();
	            	System.out.println("----------> here name transno ->"+fileItemsPresent.getString());	            	
	            }
	            
	            if(fileItemsPresent.getFieldName().equals("chkamt"))
	            {
	            	this.chkamt = fileItemsPresent.getString();	            	
	            }
	            
	            if ( !fileItemsPresent.isFormField () )	
	            {
	            	
	            String NameofField = fileItemsPresent.getFieldName();
	            String NameofFile = fileItemsPresent.getName();
	            System.out.println("----------> name field ->"+NameofField);
	            System.out.println("----------> name file ->"+NameofFile);
	            System.out.println("--------- memory>"+ fileItemsPresent.isInMemory());
	            System.out.println("--------- size>"+fileItemsPresent.getSize());	
	            
	            if( NameofFile.lastIndexOf("\\") >= 0 )
	            {
	                    
	            	chq = new File( chqPath + NameofFile.substring( NameofFile.lastIndexOf("\\"))) ;
	            	
	            }else{
	            	
	                chq = new File( chqPath + NameofFile.substring(NameofFile.lastIndexOf("\\")+1)) ;
	            }
	            
	            fileItemsPresent.write( chq ) ;
	            
	            }	           
	         }	 
	      }catch(Exception ex) {	
	    	  ses.setAttribute("chequeresult", "Cheque Upload Failure \n Please Try again");
		       try {
				response.sendRedirect("passCheque.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    	  ex.printStackTrace();
	      }
	      
	      try{
				
			    Connection connect =null;
	    	   
	    	   
		       Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
		       connect =DriverManager.getConnection("jdbc:odbc:bank","root", " ");
	           System.out.println("DB Connection created :"+connect);
	           System.out.println("------------> Database insert ");
	            System.out.println("------------> acctype--"+accType);
	            System.out.println("------------> acctype--"+accno);
	            System.out.println("------------> acctype--"+chkamt);
	            System.out.println("------------> acctype--"+chkno);
	            System.out.println("------------> acctype--"+transno);
			
			 PreparedStatement state1=connect.prepareStatement("INSERT INTO CHQREQ VALUES(?,?,?,?,?,?,?)");
			    
			    state1.setString(1,accno);
			    state1.setString(2,accType);
			    state1.setString(3,chkamt);
			    state1.setString(4,chkno);
			    state1.setString(5,transno);
			    state1.setString(6,String.valueOf(ses.getAttribute("currentID")));
			    state1.setString(7,new java.text.SimpleDateFormat("MM/dd/yyyy h:mm:ss a").format(new Date()));
			    
	   	        state1.executeUpdate();
	   	        state1.close();
	  		System.out.println("---------> connect value ------"+connect);
	  		connect.close();
	  		
	  		ses.setAttribute("chequeresult", "Cheque is uploaded succesfully for Manager approval ");
	        response.sendRedirect("passCheque.jsp");
			
		}catch(Exception e)
		{

				ses.setAttribute("chequeresult", "Cheque Deposit request for this Cheque No is already Pending ");
		        try {
					response.sendRedirect("passCheque.jsp");
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			
			System.out.println("Failed here update amount --------->"+e.getMessage());
			e.printStackTrace();
		}
		
		try{
			
			String email = "";
			String lname = "";
			

		    Connection connect =null;
  	   
  	   
	       Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
	       connect =DriverManager.getConnection("jdbc:odbc:bank","root", " ");
         System.out.println("DB Connection created :"+connect);
			
			PreparedStatement state=connect.prepareStatement("SELECT * FROM EXISTUSERS WHERE "+"CUSTOMERID="+ses.getAttribute("currentID"));
			ResultSet result=state.executeQuery();
			
			while(result.next()){
				
			      email=result.getString("EMAIL");
			      lname=result.getString("LASTNAME");
			      System.out.println("Email------------>"+email);
			      System.out.println("Lastname------------>"+lname);
			}
			
			state.close();
			
			MailNotification mail = new MailNotification(email);
			
			
		    
		    String body = "Hello "+ lname + 
			    		      "\n\n Your Cheque is successfully uploaded for Manager Approval"+
			    		      "\n\n Account : "+accType+
			    		      "\n Number : "+accno+
			    		      "\n Cheque Amount : "+chkamt+
			    		       "\n\n Status about the Cheque and Deposit will be initimated to your mail"+
			    		      "\n\n Note : Please do not reply to this E-Mail Notification";
		    
		   
		    	mail.sendMail( "Cheque Deposited", body);
			
			connect.close();
			
		}catch(Exception e){
			ses.setAttribute("chequeresult", "Cheque is uploaded succesfully for Manager approval ");
			e.printStackTrace();
			System.out.println(" -----------> Failed in Mail notification --------");
	        try {
				response.sendRedirect("passCheque.jsp");
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
		}
		
	}


}

